#include "progressdialog.h"
#include <QApplication>
#include <QHBoxLayout>
#include <QFont>
#include <QFileInfo>

ProgressDialog::ProgressDialog(QWidget *parent)
    : QDialog(parent)
{
    setWindowTitle(tr("处理中..."));
    setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint);
    setFixedSize(400, 160);

    QVBoxLayout* layout = new QVBoxLayout(this);
    layout->setSpacing(8);
    layout->setContentsMargins(15, 15, 15, 15);

    // 操作标题
    m_titleLabel = new QLabel(tr("正在处理..."), this);
    QFont titleFont = m_titleLabel->font();
    titleFont.setBold(true);
    titleFont.setPointSize(titleFont.pointSize() + 1);
    m_titleLabel->setFont(titleFont);
    layout->addWidget(m_titleLabel);

    // 当前文件名
    m_fileNameLabel = new QLabel(this);
    m_fileNameLabel->setWordWrap(true);
    m_fileNameLabel->setStyleSheet("color: #666666;");
    layout->addWidget(m_fileNameLabel);

    // 状态文本
    m_statusLabel = new QLabel(this);
    layout->addWidget(m_statusLabel);

    // 进度条
    m_progressBar = new QProgressBar(this);
    m_progressBar->setRange(0, 100);
    m_progressBar->setValue(0);
    m_progressBar->setTextVisible(true);
    layout->addWidget(m_progressBar);

    // 取消按钮
    m_cancelButton = new QPushButton(tr("取消"), this);
    layout->addWidget(m_cancelButton);

    connect(m_cancelButton, &QPushButton::clicked,
            this, &ProgressDialog::onCancelClicked);
}

void ProgressDialog::setProgress(int value, int maximum)
{
    m_progressBar->setMaximum(maximum);
    m_progressBar->setValue(value);
    QApplication::processEvents();  // 確保UI更新
}

void ProgressDialog::setStatusText(const QString& text)
{
    m_statusLabel->setText(text);
    QApplication::processEvents();  // 確保UI更新
}

void ProgressDialog::setFileName(const QString& fileName)
{
    if (fileName.isEmpty()) {
        m_fileNameLabel->hide();
    } else {
        m_fileNameLabel->setText(tr("文件: %1").arg(QFileInfo(fileName).fileName()));
        m_fileNameLabel->show();
    }
    QApplication::processEvents();
}

void ProgressDialog::setDetailedProgress(const QString& operation, int current, int total, const QString& fileName)
{
    // 更新操作标题
    m_titleLabel->setText(operation);

    // 更新文件名
    setFileName(fileName);

    // 更新进度
    setProgress(current, total);

    // 更新状态文本
    QString statusText = tr("进度: %1 / %2").arg(current).arg(total);
    if (total > 0) {
        int percentage = (current * 100) / total;
        statusText += tr(" (%1%)").arg(percentage);
    }
    setStatusText(statusText);
}

void ProgressDialog::onCancelClicked()
{
    m_canceled = true;
    emit canceled();
} 